// 全局配置
const CONFIG = {
    API_BASE_URL: 'http://localhost:8080/api',
    UPDATE_INTERVAL: 30000, // 30秒更新一次数据
    MAX_RETRIES: 3
};

// 全局状态管理
const AppState = {
    currentUser: null,
    isSidebarCollapsed: false,
    isMobileMenuOpen: false,
    pendingRequests: new Map()
};

// 工具函数
const Utils = {
    // 显示通知
    showNotification(message, type = 'info', duration = 3000) {
        // 移除已存在的通知
        const existingNotifications = document.querySelectorAll('.custom-notification');
        existingNotifications.forEach(notification => notification.remove());

        const notification = document.createElement('div');
        notification.className = 'custom-notification';
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 6px;
            color: white;
            z-index: 10000;
            max-width: 300px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            font-weight: 500;
            animation: slideInRight 0.3s ease;
        `;

        const backgroundColor = {
            'success': '#4caf50',
            'error': '#f44336',
            'warning': '#ff9800',
            'info': '#2196f3'
        }[type] || '#2196f3';

        notification.style.background = backgroundColor;
        notification.textContent = message;

        document.body.appendChild(notification);

        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, duration);
    },

    // 格式化时间
    formatTime(date) {
        return new Date(date).toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    },

    // 格式化日期
    formatDate(date) {
        return new Date(date).toLocaleDateString('zh-CN');
    },

    // 格式化日期时间
    formatDateTime(date) {
        return new Date(date).toLocaleString('zh-CN');
    },

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function (...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    // 生成随机ID
    generateId() {
        return 'id_' + Math.random().toString(36).substr(2, 9);
    },

    // 验证手机号
    validatePhone(phone) {
        return /^1[3-9]\d{9}$/.test(phone);
    },

    // 验证邮箱
    validateEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    },

    // 模拟网络延迟
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    },

    // API调用封装
    async callApi(endpoint, options = {}) {
        try {
            const fullUrl = `${CONFIG.API_BASE_URL}${endpoint}`;
            console.log('🌐 API 请求:', fullUrl);
            
            const token = localStorage.getItem('authToken');
            const headers = {
                'Content-Type': 'application/json',
                ...options.headers
            };

            if (token) {
                headers['Authorization'] = `Bearer ${token}`;
            }

            const defaultOptions = {
                headers,
                ...options
            };

            console.log('📤 请求选项:', defaultOptions);
            const response = await fetch(fullUrl, defaultOptions);
            console.log('📨 响应状态:', response.status, response.statusText);

            if (!response.ok) {
                const errorText = await response.text();
                console.error('❌ 响应错误内容:', errorText);
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const jsonData = await response.json();
            console.log('✅ 响应数据:', jsonData);
            return jsonData;
        } catch (error) {
            console.error(`❌ API调用失败 ${endpoint}:`, error);
            throw error;
        }
    }
};

// API请求封装（兼容旧版本）
class ApiClient {
    constructor(baseURL) {
        this.baseURL = baseURL;
        this.token = localStorage.getItem('authToken');
    }

    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        };

        if (this.token) {
            config.headers['Authorization'] = `Bearer ${this.token}`;
        }

        try {
            const response = await fetch(url, config);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            console.error('API request failed:', error);
            Utils.showNotification('网络请求失败，请检查连接', 'error');
            throw error;
        }
    }

    async get(endpoint) {
        return this.request(endpoint);
    }

    async post(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    async put(endpoint, data) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    async delete(endpoint) {
        return this.request(endpoint, {
            method: 'DELETE'
        });
    }

    setToken(token) {
        this.token = token;
        localStorage.setItem('authToken', token);
    }

    clearToken() {
        this.token = null;
        localStorage.removeItem('authToken');
    }
}

// 创建API客户端实例（兼容旧版本）
const apiClient = new ApiClient(CONFIG.API_BASE_URL);

// 用户服务
class UserService {
    constructor() {
        this.baseUrl = CONFIG.API_BASE_URL;
    }

    async login(credentials) {
        try {
            const data = await Utils.callApi('/auth/login', {
                method: 'POST',
                body: JSON.stringify(credentials)
            });
            return data;
        } catch (error) {
            console.error('Login failed:', error);
            throw error;
        }
    }

    async logout() {
        try {
            await Utils.callApi('/auth/logout', {
                method: 'POST'
            });
        } catch (error) {
            console.error('Logout failed:', error);
        }
        return { success: true };
    }

    async getProfile(userId) {
        try {
            return await Utils.callApi(`/users/${userId}`);
        } catch (error) {
            console.error('Get profile failed:', error);
            throw error;
        }
    }
}

// 摆渡车服务
class FerryService {
    constructor() {
        this.baseUrl = CONFIG.API_BASE_URL;
    }

    // 获取所有车辆信息
    async getVehicles() {
        try {
            const data = await Utils.callApi('/shuttle/vehicles');
            return data.vehicles || [];
        } catch (error) {
            console.error('Get vehicles failed:', error);
            return [];
        }
    }

    // 叫车请求
    async requestFerry(requestData) {
        try {
            return await Utils.callApi('/shuttle/request', {
                method: 'POST',
                body: JSON.stringify(requestData)
            });
        } catch (error) {
            console.error('Request ferry failed:', error);
            throw error;
        }
    }

    // 获取用户活跃请求
    async getActiveRequests(userId) {
        try {
            const data = await Utils.callApi(`/shuttle/user/${userId}/active-requests`);
            return data.activeRequests || [];
        } catch (error) {
            console.error('Get active requests failed:', error);
            return [];
        }
    }

    // 获取用户请求历史
    async getRequestHistory(userId) {
        try {
            const data = await Utils.callApi(`/shuttle/user/${userId}/requests`);
            return data.requests || [];
        } catch (error) {
            console.error('Get request history failed:', error);
            return [];
        }
    }

    // 取消请求
    async cancelRequest(requestId) {
        try {
            return await Utils.callApi(`/shuttle/request/${requestId}/cancel`, {
                method: 'POST'
            });
        } catch (error) {
            console.error('Cancel request failed:', error);
            throw error;
        }
    }

    // 获取系统状态
    async getSystemStatus() {
        try {
            return await Utils.callApi('/shuttle/system-status');
        } catch (error) {
            console.error('Get system status failed:', error);
            return {};
        }
    }
}

// 休息区服务
class RestAreaService {
    constructor() {
        this.baseUrl = CONFIG.API_BASE_URL;
    }

    // 获取所有休息区
    async getRestAreas() {
        try {
            const data = await Utils.callApi('/restarea/areas');
            return data.areas || [];
        } catch (error) {
            console.error('Get rest areas failed:', error);
            return [];
        }
    }

    // 获取座位图
    async getSeatingMap(areaId) {
        try {
            return await Utils.callApi(`/restarea/areas/${areaId}/seats`);
        } catch (error) {
            console.error('Get seating map failed:', error);
            throw error;
        }
    }

    // 创建预约
    async createReservation(reservationData) {
        try {
            return await Utils.callApi('/restarea/reservations', {
                method: 'POST',
                body: JSON.stringify(reservationData)
            });
        } catch (error) {
            console.error('Create reservation failed:', error);
            throw error;
        }
    }

    // 获取用户预约记录
    async getUserReservations(userId) {
        try {
            const data = await Utils.callApi(`/restarea/users/${userId}/reservations`);
            return data.reservations || [];
        } catch (error) {
            console.error('Get user reservations failed:', error);
            return [];
        }
    }

    // 取消预约
    async cancelReservation(reservationId) {
        try {
            return await Utils.callApi(`/restarea/reservations/${reservationId}/cancel`, {
                method: 'POST'
            });
        } catch (error) {
            console.error('Cancel reservation failed:', error);
            throw error;
        }
    }

    // 获取休息区统计
    async getAreaStats() {
        try {
            return await Utils.callApi('/restarea/stats');
        } catch (error) {
            console.error('Get area stats failed:', error);
            return {};
        }
    }
}

// 道具预约服务
class EquipmentService {
    constructor() {
        this.baseUrl = CONFIG.API_BASE_URL;
    }

    // 获取可用道具
    async getAvailableEquipment() {
        try {
            console.log('📡 调用 API: /equipment/available');
            const data = await Utils.callApi('/equipment/available');
            console.log('📥 API 返回数据:', data);
            console.log('📦 equipment 字段:', data.equipment);
            return data.equipment || [];
        } catch (error) {
            console.error('❌ Get equipment failed:', error);
            console.error('❌ 错误类型:', error.name);
            console.error('❌ 错误消息:', error.message);
            return [];
        }
    }

    // 预约道具
    async bookEquipment(bookingData) {
        try {
            return await Utils.callApi('/equipment/book', {
                method: 'POST',
                body: JSON.stringify(bookingData)
            });
        } catch (error) {
            console.error('Book equipment failed:', error);
            throw error;
        }
    }

    // 获取用户预约记录
    async getUserBookings(userId) {
        try {
            const data = await Utils.callApi(`/equipment/user/${userId}/bookings`);
            return data.bookings || [];
        } catch (error) {
            console.error('Get user bookings failed:', error);
            return [];
        }
    }

    // 取消预约
    async cancelBooking(bookingId) {
        try {
            return await Utils.callApi(`/equipment/bookings/${bookingId}/cancel`, {
                method: 'POST'
            });
        } catch (error) {
            console.error('Cancel booking failed:', error);
            throw error;
        }
    }

    // 获取道具分类
    async getEquipmentCategories() {
        try {
            const data = await Utils.callApi('/equipment/categories');
            return data.categories || [];
        } catch (error) {
            console.error('Get categories failed:', error);
            return [];
        }
    }

    // 获取道具库存状态
    async getEquipmentStatus(equipmentId) {
        try {
            return await Utils.callApi(`/equipment/${equipmentId}/status`);
        } catch (error) {
            console.error('Get equipment status failed:', error);
            throw error;
        }
    }
}

// 项目推荐服务
class ProjectRecommendService {
    constructor() {
        this.baseUrl = CONFIG.API_BASE_URL;
    }

    // 获取推荐项目
    async getRecommendations(userId) {
        try {
            const data = await Utils.callApi(`/recommend/projects/${userId}`);
            return data.recommendations || [];
        } catch (error) {
            console.error('Get recommendations failed:', error);
            return [];
        }
    }

    // 获取实时排队信息
    async getQueueInfo() {
        try {
            const data = await Utils.callApi('/recommend/queue-info');
            return data.queues || [];
        } catch (error) {
            console.error('Get queue info failed:', error);
            return [];
        }
    }
}

// 订餐服务
class FoodService {
    constructor() {
        this.baseUrl = CONFIG.API_BASE_URL;
    }

    // 获取餐厅列表
    async getRestaurants() {
        try {
            const data = await Utils.callApi('/food/restaurants');
            return data.restaurants || [];
        } catch (error) {
            console.error('Get restaurants failed:', error);
            return [];
        }
    }

    // 下单
    async placeOrder(orderData) {
        try {
            return await Utils.callApi('/food/orders', {
                method: 'POST',
                body: JSON.stringify(orderData)
            });
        } catch (error) {
            console.error('Place order failed:', error);
            throw error;
        }
    }

    // 获取用户订单
    async getUserOrders(userId) {
        try {
            const data = await Utils.callApi(`/food/user/${userId}/orders`);
            return data.orders || [];
        } catch (error) {
            console.error('Get user orders failed:', error);
            return [];
        }
    }
}

// 创建服务实例
const userService = new UserService();
const ferryService = new FerryService();
const restAreaService = new RestAreaService();
const equipmentService = new EquipmentService();
const projectRecommendService = new ProjectRecommendService();
const foodService = new FoodService();

// 侧边栏功能
function toggleSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const collapseBtn = document.querySelector('.collapse-btn');
    const mainContent = document.querySelector('.main-content');

    AppState.isSidebarCollapsed = !AppState.isSidebarCollapsed;
    sidebar.classList.toggle('collapsed');

    if (AppState.isSidebarCollapsed) {
        collapseBtn.innerHTML = '▶';
        localStorage.setItem('sidebarCollapsed', 'true');
    } else {
        collapseBtn.innerHTML = '◀';
        localStorage.setItem('sidebarCollapsed', 'false');
    }
}

// 移动端菜单功能
function toggleMobileMenu() {
    const sidebar = document.querySelector('.sidebar');
    AppState.isMobileMenuOpen = !AppState.isMobileMenuOpen;
    sidebar.classList.toggle('mobile-open');
}

// 页面导航
function navigateTo(page) {
    window.location.href = page;
}

function goBack() {
    window.history.back();
}

// 用户认证相关
async function loginUser(credentials) {
    try {
        const data = await userService.login(credentials);
        AppState.currentUser = data.user;
        localStorage.setItem('currentUser', JSON.stringify(data.user));
        localStorage.setItem('authToken', data.token);
        Utils.showNotification('登录成功', 'success');
        return data;
    } catch (error) {
        Utils.showNotification('登录失败', 'error');
        throw error;
    }
}

async function logoutUser() {
    try {
        await userService.logout();
        AppState.currentUser = null;
        localStorage.removeItem('currentUser');
        localStorage.removeItem('authToken');
        Utils.showNotification('已退出登录', 'info');
        navigateTo('login.html');
    } catch (error) {
        console.error('Logout failed:', error);
    }
}

function getCurrentUser() {
    if (AppState.currentUser) {
        return AppState.currentUser;
    }

    const storedUser = localStorage.getItem('currentUser');
    if (storedUser) {
        AppState.currentUser = JSON.parse(storedUser);
        return AppState.currentUser;
    }

    return null;
}

// 摆渡车相关函数
async function callFerry(requestData) {
    try {
        const result = await ferryService.requestFerry(requestData);
        Utils.showNotification('摆渡车呼叫成功！', 'success');
        return result;
    } catch (error) {
        Utils.showNotification('呼叫失败，请重试', 'error');
        throw error;
    }
}

async function getFerryVehicles() {
    return await ferryService.getVehicles();
}

async function getActiveFerryRequests(userId) {
    return await ferryService.getActiveRequests(userId);
}

async function getFerryRequestHistory(userId) {
    return await ferryService.getRequestHistory(userId);
}

async function cancelFerryRequest(requestId) {
    try {
        await ferryService.cancelRequest(requestId);
        Utils.showNotification('叫车已取消', 'info');
        return { success: true };
    } catch (error) {
        Utils.showNotification('取消失败，请重试', 'error');
        throw error;
    }
}

// 休息区相关函数
async function getRestAreas() {
    return await restAreaService.getRestAreas();
}

async function getSeatingMap(areaId) {
    return await restAreaService.getSeatingMap(areaId);
}

async function createReservation(reservationData) {
    try {
        const result = await restAreaService.createReservation(reservationData);
        Utils.showNotification('休息区预约成功！', 'success');
        return result;
    } catch (error) {
        Utils.showNotification('预约失败，请重试', 'error');
        throw error;
    }
}

async function getUserReservations(userId) {
    return await restAreaService.getUserReservations(userId);
}

async function cancelReservation(reservationId) {
    try {
        await restAreaService.cancelReservation(reservationId);
        Utils.showNotification('预约已取消', 'info');
        return { success: true };
    } catch (error) {
        Utils.showNotification('取消失败，请重试', 'error');
        throw error;
    }
}

// 道具预约相关函数
async function getAvailableEquipment() {
    return await equipmentService.getAvailableEquipment();
}

async function bookEquipment(bookingData) {
    try {
        const result = await equipmentService.bookEquipment(bookingData);
        Utils.showNotification('道具预约成功！', 'success');
        return result;
    } catch (error) {
        Utils.showNotification('预约失败，请重试', 'error');
        throw error;
    }
}

async function getUserBookings(userId) {
    return await equipmentService.getUserBookings(userId);
}

async function cancelBooking(bookingId) {
    try {
        await equipmentService.cancelBooking(bookingId);
        Utils.showNotification('预约已取消', 'info');
        return { success: true };
    } catch (error) {
        Utils.showNotification('取消失败，请重试', 'error');
        throw error;
    }
}

async function getEquipmentCategories() {
    return await equipmentService.getEquipmentCategories();
}

// 初始化函数
function initializeApp() {
    // 恢复侧边栏状态
    const sidebarCollapsed = localStorage.getItem('sidebarCollapsed');
    if (sidebarCollapsed === 'true') {
        toggleSidebar();
    }

    // 设置当前用户
    const user = getCurrentUser();
    if (user) {
        updateUserInterface(user);
    }

    // 移动端菜单事件
    const mobileMenuBtn = document.querySelector('.mobile-menu-btn');
    if (mobileMenuBtn) {
        mobileMenuBtn.addEventListener('click', toggleMobileMenu);
    }

    // 设置活跃导航项
    setActiveNavItem();

    // 添加全局错误处理
    window.addEventListener('error', (event) => {
        console.error('Global error:', event.error);
        Utils.showNotification('发生未知错误', 'error');
    });

    // 添加页面卸载清理
    window.addEventListener('beforeunload', () => {
        // 清理未完成的请求
        AppState.pendingRequests.forEach((controller, url) => {
            controller.abort();
        });
    });
}

// 更新用户界面
function updateUserInterface(user) {
    // 更新导航栏用户信息
    const userActions = document.querySelector('.user-actions');
    if (userActions && !userActions.querySelector('.user-info')) {
        const userInfo = document.createElement('div');
        userInfo.className = 'user-info';
        userInfo.innerHTML = `
            <span class="user-name">${user.name}</span>
            <button class="btn btn-sm btn-secondary" onclick="logoutUser()">退出</button>
        `;
        userActions.appendChild(userInfo);
    }

    // 更新页面中的用户信息
    const userNameElements = document.querySelectorAll('#userName');
    userNameElements.forEach(element => {
        element.textContent = user.name;
    });

    // 显示高优先级标识
    const priorityIndicator = document.getElementById('priorityIndicator');
    if (priorityIndicator && user.priority === 'high') {
        priorityIndicator.style.display = 'block';
    }
}

// 设置活跃导航项
function setActiveNavItem() {
    const currentPage = window.location.pathname.split('/').pop();
    const navItems = document.querySelectorAll('.nav-item');

    navItems.forEach(item => {
        const href = item.getAttribute('href');
        if (href === currentPage) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    initializeApp();

    // 添加CSS动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes slideOutRight {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
            color: white;
        }
        
        .user-name {
            font-weight: 500;
        }
    `;
    document.head.appendChild(style);
});

// 导出到全局作用域
window.toggleSidebar = toggleSidebar;
window.toggleMobileMenu = toggleMobileMenu;
window.navigateTo = navigateTo;
window.goBack = goBack;
window.logoutUser = logoutUser;
window.Utils = Utils;
window.apiClient = apiClient;
window.AppState = AppState;

// 导出服务实例
window.userService = userService;
window.ferryService = ferryService;
window.restAreaService = restAreaService;
window.equipmentService = equipmentService;
window.projectRecommendService = projectRecommendService;
window.foodService = foodService;

// 导出摆渡车相关函数
window.callFerry = callFerry;
window.getFerryVehicles = getFerryVehicles;
window.getActiveFerryRequests = getActiveFerryRequests;
window.getFerryRequestHistory = getFerryRequestHistory;
window.cancelFerryRequest = cancelFerryRequest;

// 导出休息区相关函数
window.getRestAreas = getRestAreas;
window.getSeatingMap = getSeatingMap;
window.createReservation = createReservation;
window.getUserReservations = getUserReservations;
window.cancelReservation = cancelReservation;

// 导出道具预约相关函数
window.getAvailableEquipment = getAvailableEquipment;
window.bookEquipment = bookEquipment;
window.getUserBookings = getUserBookings;
window.cancelBooking = cancelBooking;
window.getEquipmentCategories = getEquipmentCategories;

// 开发模式：自动登录测试用户
if (window.location.href.includes('file://') || window.location.hostname === 'localhost') {
    const testUser = {
        id: 'dev-user-001',
        name: '开发测试用户',
        level: 'gold',
        priority: 'high'
    };

    if (!localStorage.getItem('currentUser')) {
        localStorage.setItem('currentUser', JSON.stringify(testUser));
        console.log('自动设置测试用户:', testUser);
    }
}

console.log('游乐园信息管理系统已初始化（后端对接模式）');